<template>
  <div class="bindTel-page">
    <page-header />
    <div class="bindTel-page-main">
      <a-button v-if="pageType !== 3" class="close-btn iconfont icon-with-btn" type="text" @click="router.replace('/login')">
        <i class="iconfont icon-close-line"></i>
      </a-button>
      <!-- 第一步 -->
      <a-spin :spinning="loading" size="large" tip="加载中...">
        <div v-if="pageType == 1" class="form-wrapper">
          <div class="title">绑定手机号</div>
          <a-form class="form" :model="bindTel" @finish="telFinish">
            <a-form-item
              name="tel"
              :rules="[
                { required: true, message: '请输入手机号' },
                {
                  pattern: regex.phone,
                  message: '请输入正确的手机号'
                }
              ]"
            >
              <a-input
                v-model:value="bindTel.tel"
                v-trim
                class="tel-input"
                size="large"
                addon-before="+86"
                :maxlength="11"
                placeholder="请输入手机号"
              />
            </a-form-item>
            <a-form-item>
              <a-button type="primary" html-type="submit" class="step-btn">下一步</a-button>
            </a-form-item>
          </a-form>
        </div>
        <!-- 第二部 -->
        <div v-else-if="pageType == 2" class="form-wrapper">
          <div class="title">短信验证</div>
          <a-form ref="smsFromRef" class="form" :model="smsFrom" @finish="smsLogin">
            <a-form-item name="tel">
              <a-input
                v-model:value="bindTel.tel"
                v-trim
                class="tel-input"
                size="large"
                addon-before="+86"
                :maxlength="11"
                placeholder="请输入手机号"
                disabled
              />
            </a-form-item>
            <a-form-item name="code" :rules="[{ required: true, message: '请输入验证码', trigger: 'change' }]">
              <div class="auth-code-wrapper">
                <a-input v-model:value="smsFrom.code" v-trim size="large" :maxlength="8" placeholder="请输入验证码" />
                <a-button size="large" :disabled="counter ? true : false" @click="sendSms">
                  <div class="btn-code">{{ counter ? counter + 's' : '获取验证码' }}</div>
                </a-button>
              </div>
            </a-form-item>
            <a-form-item>
              <a-space>
                <a-button type="primary" html-type="submit">绑定并登录</a-button>
                <a-button @click="changeType(1)">上一步</a-button>
              </a-space>
            </a-form-item>
          </a-form>
        </div>
      </a-spin>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { FormInstance, message } from 'ant-design-vue'
  import { regex, storage, useCountDown } from 'g6-fn'
  import { reactive, ref } from 'vue'
  import { useRequest } from 'vue-request'
  import { useRoute, useRouter } from 'vue-router'

  import { loginApi } from '@/services/api'
  import { useUserInfoStore } from '@/store'

  import PageHeader from './components/BindPhoneHeader.vue'

  const userInfoStore = useUserInfoStore()
  const route = useRoute()
  const router = useRouter()
  if (storage.get('token')) {
    router.replace('/')
  }

  const wxCode = route.query.wxCode // 路由传入微信扫码登录的ID
  const smsFrom = reactive({
    code: '',
    tel: '',
    securityCode: ''
  })

  /**
   * 切换步骤
   * 1：绑定手机号   2：短信验证   3：loading
   */
  const pageType = ref(1)
  const changeType = (type: number) => {
    smsFromRef.value?.resetFields()
    pageType.value = type
  }

  /**
   * 第一步
   */
  const bindTel = reactive({
    tel: ''
  })
  const telFinish = () => {
    if (smsFrom.tel !== bindTel.tel && smsFrom.tel) {
      smsFromRef.value?.validateFields('checkPass')
    }
    smsFrom.tel = bindTel.tel
    changeType(2)
  }

  /**
   * 第二步
   */
  const smsFromRef = ref<FormInstance>()
  const { counter, start } = useCountDown()
  const { runAsync: runSendSms } = useRequest<{ headers: { 'security-code': string } }>(loginApi.sendSms, {
    onSuccess: res => {
      smsFrom.securityCode = res.headers['security-code']
      message.success('短信验证码发送成功')
      start(60)
    },
    onError: (err: any) => {
      if (err.code === 'AUTH-100007') {
        smsFromRef.value?.resetFields()
        changeType(1)
      }
    }
  })
  const sendSms = async () => {
    await smsFromRef.value?.validateFields(['tel'])
    let params = {
      tel: smsFrom.tel,
      messageType: 2
    }
    runSendSms(params)
  }
  const { loading, runAsync: runBindingLogin } = useRequest<ResponseData<any>>(loginApi.bindingLogin, {
    onSuccess: async res => {
      userInfoStore.changeToken(res.data.token)
      await userInfoStore.getUserInfo()
      await userInfoStore.getMenuData()
      router.replace('/')
    }
  })
  const smsLogin = () => {
    let params = { weChatBindingCode: wxCode }
    Object.assign(params, smsFrom)
    runBindingLogin(params)
  }
</script>

<style lang="less" scoped>
  @import '../styles/index.less';

  .bindTel-page {
    display: flex;
    min-width: @min-width;
    height: 100vh;
    flex-direction: column;

    .ant-btn-primary {
      color: #fff;
      background: linear-gradient(180deg, #81b1ff 0%, #1868e9 100%);
      border: none;
      box-shadow: 0 2px #0000000b;
    }

    .bindTel-page-main {
      position: relative;
      display: flex;
      justify-content: center;
      align-items: center;
      width: 100%;
      flex: 1;

      .title {
        margin-bottom: 56px;
        font-size: 24px;
        font-weight: 700;
      }

      .form-wrapper {
        padding: 0 16px;
        margin: 0 auto;
        width: 462px;
        height: 300px;

        .form {
          .ant-form-item {
            margin-bottom: 40px;

            &:nth-child(3) {
              margin-bottom: 0;
              .auth-code-wrapper();
            }
          }
        }
      }
    }
  }
</style>
